"""
使用ViewSet来演示自定义视图方法映射
"""
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from .serializers import *
from .models import *

# 需求：修改书本的阅读量,部分更新
# PATCH + /books/<pk>/ = self.read

class BooksViewSet(ViewSet):

    # 自定义方法read实现修改阅读量
    def read(self, request, pk):
        # request.data = {"bread": 100}
        book = BookInfo.objects.get(pk=pk)
        bs = BookInfoModelSerializer(
            instance=book,
            data=request.data,
            partial=True
        )
        if not bs.is_valid():
            return Response(bs.errors, status=400)

        bs.save()

        return Response(bs.data)